<?php 
class ControllerProductSearch extends FrontController { 	
	public function index() {
		
		M('catalog/category');		
		M('catalog/product');		
		
		$filter_name = $this->request->get('search', '');		
		$filter_description = $this->request->get('description', '');
		$filter_category_id = $this->request->get('category_id', 0);
		$filter_sub_category = $this->request->get('sub_category', '');
		$sort = $this->request->get('sort', 'p.sort_order');
		$order = $this->request->get('order', 'ASC');
		$page = $this->request->get('page', 1);
		$limit = $this->request->get('limit', C('config_catalog_limit'));
		
		if (!range_length($filter_name, C('config_search_min_keyword_length'), C('config_search_max_keyword_length'))) {
			$this->data['error_warning'] = sprintf($this->_['error_keyword'], C('config_search_min_keyword_length'), C('config_search_max_keyword_length'));
			$filter_name = '';
		}
		
		if ($filter_name) {
			$this->document->setTitle($this->_['heading_title'] .  ' - ' . $filter_name);
		} else {
			$this->document->setTitle($this->_['heading_title']);
		}

		$url = '';		
		if ($filter_name) {
			$url .= '&filter_name=' . urlencode(v5_html_entity_decode($filter_name));
		}
		$_url = $this->request->query('filter_description,filter_category_id,filter_sub_category,sort,order,page,limit');
		if ($_url) $url .= '&' . $_url;
		
   		$this->data['breadcrumbs'][] = array(
       		'text'      => $this->_['heading_title'],
			'href'      => U('product/search', $url),
      		'separator' => $this->_['text_separator']
   		);
		
		if ($filter_name) {
    		$this->data['heading_title'] = $this->_['heading_title'] .  ' - ' . $filter_name;
		} else {
			$this->data['heading_title'] = $this->_['heading_title'];
		}
		$this->data['text_compare'] = sprintf($this->_['text_compare'], (isset($this->session->data['compare']) ? count($this->session->data['compare']) : 0));
		
		M('catalog/category');
		
		// 3 Level Category Search
		$this->data['categories'] = array();
		
		$categories_1 = $this->model_catalog_category->getCategories(0);
		
		foreach ($categories_1 as $category_1) {
			$level_2_data = array();
			
			$categories_2 = $this->model_catalog_category->getCategories($category_1['category_id']);
			
			foreach ($categories_2 as $category_2) {
				$level_3_data = array();
				
				$categories_3 = $this->model_catalog_category->getCategories($category_2['category_id']);
				
				foreach ($categories_3 as $category_3) {
					$level_3_data[] = array(
						'category_id' => $category_3['category_id'],
						'name'        => $category_3['name'],
					);
				}
				
				$level_2_data[] = array(
					'category_id' => $category_2['category_id'],	
					'name'        => $category_2['name'],
					'children'    => $level_3_data
				);					
			}
			
			$this->data['categories'][] = array(
				'category_id' => $category_1['category_id'],
				'name'        => $category_1['name'],
				'children'    => $level_2_data
			);
		}
		$this->data['products'] = array();
		
		if ($filter_name) {
			$data = array(
				'filter_name'         => $filter_name, 
				'filter_description'  => $filter_description,
				'filter_category_id'  => $filter_category_id, 
				'filter_sub_category' => $filter_sub_category, 
				'sort'                => $sort,
				'order'               => $order,
				'start'               => ($page - 1) * $limit,
				'limit'               => $limit
			);
					
			$product_total = $this->model_catalog_product->getTotalProducts($data);
								
			$results = $this->model_catalog_product->getProducts($data);
					
			foreach ($results as $result) {
				
				$this->data['products'][] = array(
					'product_id'  => $result['product_id'],
					'thumb'       => thumb($result['image'], C('config_image_product_width'), C('config_image_product_height')),
					'name'        => $result['name'],
					'summary'     => v5_html_entity_decode($result['summary']),
					'price'       => pprintf($result['price'], $result['tax_class_id']),
					'special'     => pprintf($result['special'], $result['tax_class_id']),
					'tax'         => C('config_tax') ? currency((float)$result['special'] ? $result['special'] : $result['price']) : false,
					'rating'      => C('config_review_status') ? $result['rating'] : false,
					'reviews'     => sprintf($this->_['text_reviews'], (int)$result['reviews']),
					'href'        => $result['link'],
				);
			}
					
			$url = '';
			
			if ($filter_name) {
				$url .= '&search=' . urlencode(v5_html_entity_decode($filter_name));
			}
			
			$_url = $this->request->query('filter_description,filter_category_id,filter_sub_category,limit');
			if ($_url) $url .= '&' . $_url;
			
			$this->data['sorts'] = array();
			
			$this->data['sorts'][] = array(
				'text'  => $this->_['text_default'],
				'value' => 'sort_order-asc',
				'href'  => U('product/search', 'sort=sort_order&order=asc' . $url)
			);
			
			$this->data['sorts'][] = array(
				'text'  => $this->_['text_price_asc'],
				'value' => 'price-asc',
				'href'  => U('product/search', 'sort=price&order=asc' . $url)
			); 
	
			$this->data['sorts'][] = array(
				'text'  => $this->_['text_price_desc'],
				'value' => 'price-desc',
				'href'  => U('product/search', 'sort=price&order=desc' . $url)
			); 
			
			$this->data['sorts'][] = array(
					'text'  => $this->_['text_release_date'],
					'value' => 'date_added-desc',
					'href'  => U('product/search', 'sort=date_added&order=desc' . $url)
			);
			
			if (C('config_review_status')) {
				$this->data['sorts'][] = array(
					'text'  => $this->_['text_rating_desc'],
					'value' => 'rating-desc',
					'href'  => U('product/search', 'sort=rating&order=desc' . $url)
				);
				
				$this->data['sorts'][] = array(
					'text'  => $this->_['text_most_reviews'],
					'value' => 'reviews-desc',
					'href'  => U('product/search', 'sort=reviews&order=desc' . $url)
				);
			}
			
	
			$url = '';
			
			if ($filter_name) {
				$url .= '&filter_name=' . urlencode(v5_html_entity_decode($filter_name));
			}
			$_url = $this->request->query('filter_description,filter_category_id,filter_sub_category,sort,order');
			if ($_url) $url .= '&' . $_url;
			
			$this->data['limits'] = array();
			
			$this->data['limits'][] = array(
				'text'  => C('config_catalog_limit'),
				'value' => C('config_catalog_limit'),
				'href'  => U('product/search', $url . '&limit=' . C('config_catalog_limit'))
			);
			
			for($i = 25; $i <= 100; $i += 25) {
				$this->data['limits'][] = array(
					'text'  => $i,
					'value' => $i,
					'href'  => U('product/search', $url . "&limit=$i")
				);
			}
							
			$url = '';	
			if ($filter_name) {
				$url .= '&filter_name=' . urlencode(v5_html_entity_decode($filter_name));
			}
			$_url = $this->request->query('filter_description,filter_category_id,filter_sub_category,sort,order,limit');
			if ($_url) $url .= '&' . $_url;
			
			$url = U('product/search', $url . '&page={page}');			
			$this->data['pagination'] = $this->pagination($product_total, $page, $url, $limit)->render();
			
			if ($page == 1)	$this->keyword($filter_name, $product_total);
		}	
		
		$this->data['filter_name'] = $filter_name;
		$this->data['filter_description'] = $filter_description;
		$this->data['filter_category_id'] = $filter_category_id;
		$this->data['filter_sub_category'] = $filter_sub_category;
				
		$this->data['sort'] = $sort;
		$this->data['order'] = $order;
		$this->data['limit'] = $limit;
		
		$this->display('product/search.tpl');
  	}
  	
  	protected function keyword($kw, $items) {
  		global $V5_TIME, $V5_NOW;
  		
  		if(!C('config_search_keyword_log') || strlen($kw) < 3 || strlen($kw) > 100) return;
  		
  		$r = $this->db->queryOne("SELECT * FROM @@keyword WHERE keyword='" . ES($kw) . "'");
  		
  		if($r) {
  			$items = $items > $r['items'] ? $items : $r['items'];
  			$month_search = v5_date_format($r['date_updated'],'Y-m') == date('Y-m', $V5_TIME) ? 'month_search+1' : '1';
  			$week_search = v5_date_format($r['date_updated'], 'W') == date('W', $V5_TIME) ? 'week_search+1' : '1';
  			$today_search = v5_date_format($r['date_updated'], 'Y-m-d') == date('Y-m-d', $V5_TIME) ? 'today_search+1' : '1';
  			$this->db->runSql("UPDATE @@keyword SET items = $items, date_updated = '$V5_NOW', total_search = total_search + 1,
  					month_search = $month_search, week_search = $week_search, today_search = $today_search
  					WHERE keyword_id = $r[keyword_id]");
  		} else {  			
  			$this->db->runSql("INSERT INTO @@keyword (keyword, items, date_updated, total_search, month_search, week_search,
  					 today_search) VALUES ('$kw', $items, '$V5_NOW', 1, 1, 1, 1)");
  		}
  	}
}
?>